package com.iris.live.services.report.sources;

import com.iris.live.services.common.StringUtils;
import com.iris.live.services.data.models.ReportConfig;
import com.iris.live.services.report.data.BaseReportDataSource;
import com.iris.live.services.report.data.ReportContext;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SalesFunnelClueDataSource
 *
 * @author sallygo
 * @date 2017/12/28 18:09
 */
@Component("SalesFunnelClueDataSource")
public class SalesFunnelClueDataSource extends BaseReportDataSource {
    @Override
    public List getData(ReportContext context, List<ReportConfig> config) throws Exception {
        Map info= context.getParams() ;
        String lineType=info.get("displayType").toString();
        List<Map> datas =new ArrayList<>();
        if("1".equals(lineType)){
            datas = getClueTimeLineData(info);
        }
        super.brandGroup(context ,datas);
        return datas;
    }

    private List getClueTimeLineData(Map info) {
        Map params = new HashMap();
        StringBuffer sql = new StringBuffer("select  " +
                "  a.permit, " +
                "  right(a.sale_month,2) as date, " +
                "  sum(a.clue_num) clue_num , " +
                "  sum(a.new_clue_num) new_clue_num " +
                " from t_rpt_data_sale_info a " +
                " join lsh经销商表 b on a.permit = b.`许可_BMBS` " +
                " join lsh车型 c on a.vehicle_model_id = c.`车型编号` " +
                " where 1=1 ");

        String startMonth = info.get("startMonth") == null ?"":info.get("startMonth").toString(),
                endMonth = info.get("endMonth") == null ?"":info.get("endMonth").toString();
        if (! StringUtils.isNullOrBlank(startMonth)  && ! StringUtils.isNullOrBlank(endMonth)) {
            sql.append(" and a.sale_month >= :startMonth and a.sale_month <= :endMonth ");
            params.put("startMonth",startMonth);
            params.put("endMonth",endMonth);
        }

        String orgTerm = getOrgTerms("b", info, params);
        if(StringUtils.isNotNullOrBlank(orgTerm)){
            sql.append(" and ").append(orgTerm);
        }

        String carType = info.get("carType") == null ?"":info.get("carType").toString();
        if (! StringUtils.isNullOrBlank(carType) && !"all".equalsIgnoreCase(carType) && !"全部".equalsIgnoreCase(carType)) {
            sql.append(" and (c.品牌 = :carType or c.级别 = :carType or c.车型 = :carType) ");
            params.put("carType",carType);
        }
        sql.append(" group by date order by date asc ");
        return this.getList(sql.toString(),params);
    }


}
